#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Y-aong
 @FileName: schema_utils.py
 @DateTime: 2024/6/11 22:10
 @Version : 3.10
 @Description: schema工具类
"""
import json
import traceback
import typing
from marshmallow.fields import Nested

from public.logger import logger


class CustomNested(Nested):
    def serialize(
            self,
            attr: str,
            obj: typing.Any,
            accessor: typing.Any = None,
            **kwargs
    ) -> typing.Union[dict, list]:
        """
        序列化嵌套字段。
        :param attr: 属性名称。
        :param obj: 要序列化的对象。
        :param accessor: 对象的访问器。
        :param kwargs: 额外的关键字参数。
        :return: 序列化结果。
        """
        result = super().serialize(attr, obj, accessor, **kwargs)
        if isinstance(result, list):
            result = [item for item in result if item.get('active')]
        elif isinstance(result, dict) and not result.get('active'):
            result = {}

        return result


def columns_to_json(obj, attribute: str, default=''):
    try:
        if not hasattr(obj, attribute):
            raise AttributeError(f'{obj}没有属性为{attribute}, ')
        attribute_value = getattr(obj, attribute)

        if attribute_value and isinstance(attribute_value, str):
            attribute_value = json.loads(attribute_value)
        return json.dumps(attribute_value, indent=2, ensure_ascii=False) if attribute_value else ""
    except Exception as e:
        logger.error(f'字段{attribute}变成json失败:{e},\n详细信息::{traceback.format_exc()}')
        return default
